layui.define(['jquery', 'layer'], function (exports) {
    var $ = layui.$;
    var layer = layui.layer;

    function isObject(obj) {
        return Object.prototype.toString.call(obj) === '[object Object]'
    }

    function uuidv4() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    class ExBase {
        AJAX_SUCCESS_CODE = 0
        common_ajax_error = function (XMLHttpRequest, textStatus, errorThrown) {
            layer.closeAll('loading');
            if (XMLHttpRequest.readyState == 4) {
                var data = JSON.parse(XMLHttpRequest.responseText);
                layer.msg('失败：' + data.msg, {icon: 2});
            } else {
                layer.msg('请求执行失败', {icon: 2});
            }
        }
        generateId = function (prefix) {
            return (prefix || "random") + "_" + uuidv4();
        }

        /**
         * 读取表单中的值，并且转换为一个Key-Value对象
         * 如果表单的key包含"."，则会创建嵌套的对象,
         * 果存在相同的Key，将会创建一个JS数组存放数据
         * @param $form
         * @returns {{}}
         */
        getFormAsJson = function ($form) {
            var indexed_array = {};
            var unindexed_array = []

            var nameIndex = {} ,fieldElem = $form.find('input,select,textarea') //获取所有表单域
            layui.each(fieldElem, function(_, item){
                item.name = (item.name || '').replace(/^\s*|\s*&/, '');

                if(!item.name) return;

                //用于支持数组 name
                if(/^.*\[\]$/.test(item.name)){
                    var key = item.name.match(/^(.*)\[\]$/g)[0];
                    nameIndex[key] = nameIndex[key] | 0;
                    item.name = item.name.replace(/^(.*)\[\]$/, '$1['+ (nameIndex[key]++) +']');
                }
                var multiple = $(item).attr('multiple')
                if(/^checkbox|radio$/.test(item.type) && !item.checked) return;
                var value = item.value
                if(item.nodeName === 'SELECT' && multiple){
                    value = [];
                    var options = item && item.options;
                    var opt;
                    for (var i=0, iLen=options.length; i<iLen; i++) {
                        opt = options[i];
                        if (opt.selected) {
                            value.push(opt.value || opt.text);
                        }
                    }
                }

                unindexed_array.push({name: item.name, value: value, multiple : multiple})
            });

            $.map(unindexed_array, function (n, i) {
                var names = n['name'].split(".")
                var parent = indexed_array;
                var multiple = n['multiple']
                $.each(names, function (index, e) {
                    if (index == names.length - 1) {
                        if (parent[e]) {
                            if (parent[e] instanceof Array) {
                                parent[e].push(n['value'])
                            } else {
                                var preValue = parent[e]
                                parent[e] = new Array()
                                parent[e].push(preValue)
                                parent[e].push(n['value'])
                            }
                        } else {
                            parent[e] = multiple && !(n['value'] instanceof Array)? [n['value']] : n['value']
                        }
                    } else {
                        if (!parent[e]) {
                            parent[e] = new Object()
                        }
                    }
                    parent = parent[e]
                })
            });
            return indexed_array;
        }

        /**
         * 读取一个JSON对象，转换成一个普通Key-Value对象，如果JSON对象中包括嵌套对象，则Key为嵌套对象，则将嵌套对象打平
         * @param data
         */
        getJsonAsForm = function (data) {
            return this.getJsonAsFormRescurily({}, "", data)
        }

        getJsonAsFormRescurily = function (obj, parentKey, data) {
            if (data == null)
                return obj;
            for (var i in data) {
                var tmpKey = i;
                if (parentKey) {
                    tmpKey = parentKey + "." + tmpKey;
                }
                if (isObject(data[i])) {
                    this.getJsonAsFormRescurily(obj, tmpKey, data[i])
                } else if (Array.isArray(data[i])) {
                    obj[tmpKey] = data[i].join(",")
                } else {
                    obj[tmpKey] = data[i]
                }
            }
            return obj;
        }
        /**
         * Create CSS Rules to Document
         * @param name
         * @param rules
         */
        createClass = function (name, rules) {
            var style = document.createElement('style');
            style.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(style);
            if (!(style.sheet || {}).insertRule)
                (style.styleSheet || style.sheet).addRule(name, rules);
            else
                style.sheet.insertRule(name + "{" + rules + "}", 0);
        }
        // createClass('.whatever',"background-color: green;");
    }

    const obj = new ExBase();
    $.ajaxSetup({
        error: obj.common_ajax_error,
        traditional: true
    });
    exports('exbase', obj); //注意，这里是模块输出的核心，模块名必须和 use 时的模块名一致
});